<template>
    <div class="page-container" v-loading="loading">
        <el-page-header @back="goBack" content="交易修正"></el-page-header>

        <el-card class="mt-4" v-if="originalDetail.id">
            <template #header>
                <div class="card-header">
                    <span>修正目标信息</span>
                </div>
            </template>
            <el-descriptions :column="2" border>
                <el-descriptions-item label="原订单ID">{{ route.params.orderId }}</el-descriptions-item>
                <el-descriptions-item label="失败明细ID">{{ originalDetail.id }}</el-descriptions-item>
                <el-descriptions-item label="基金代码">{{ originalDetail.fundCode }}</el-descriptions-item>
                <el-descriptions-item label="计划金额">{{ originalDetail.amount?.toFixed(2) }}</el-descriptions-item>
                <el-descriptions-item label="方向">{{ originalDetail.direction }}</el-descriptions-item>
                <el-descriptions-item label="状态">
                    <el-tag type="danger">{{ originalDetail.status }}</el-tag>
                </el-descriptions-item>
            </el-descriptions>
        </el-card>
        <el-alert v-else-if="!loading" title="未能加载原始订单明细" type="error" show-icon :closable="false" />


        <el-card class="mt-4">
            <template #header>
                <span>创建修正订单</span>
            </template>
            <el-form :model="form" ref="correctionFormRef" :rules="rules" label-width="120px">
                <el-form-item label="新的基金代码" prop="newFundCode">
                    <el-input v-model="form.newFundCode" placeholder="输入新的基金代码"></el-input>
                </el-form-item>
                <el-form-item label="新的交易金额" prop="amount">
                    <el-input-number v-model="form.amount" :precision="2" :step="100" :min="0"
                        style="width: 100%;"></el-input-number>
                </el-form-item>
                <el-form-item label="修正原因" prop="reason">
                    <el-input v-model="form.reason" type="textarea" placeholder="请详细说明修正原因"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitCorrection" :loading="submitting">提交修正</el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import axios from 'axios';
import { useAuthStore } from '@/store/auth';

const route = useRoute();
const router = useRouter();
const authStore = useAuthStore();

const loading = ref(true);
const submitting = ref(false);
const originalDetail = ref({});
const correctionFormRef = ref(null);

const form = reactive({
    failedOrderDetailId: null,
    newFundCode: '',
    amount: null,
    reason: '',
    approverId: null
});

const rules = {
    newFundCode: [{ required: true, message: '新的基金代码不能为空', trigger: 'blur' }],
    amount: [{ required: true, message: '新的交易金额不能为空', trigger: 'blur' }],
    reason: [{ required: true, message: '修正原因不能为空', trigger: 'blur' }]
};

const tradeApi = {
    getTradeOrderDetails: (id) => axios.get(`/api/trade/order/${id}`),
    createCorrection: (data) => axios.post('/api/trade/corrections', data)
};


const goBack = () => {
    router.back();
};

const submitCorrection = async () => {
    if (!correctionFormRef.value) return;
    await correctionFormRef.value.validate(async (valid) => {
        if (valid) {
            submitting.value = true;
            try {
                const response = await tradeApi.createCorrection(form);
                ElMessage.success('交易修正成功，已生成新的交易订单！');
                // 跳转到新生成的订单详情页
                router.push({ name: 'TradeOrderDetail', params: { id: response.data.id } });
            } catch (error) {
                ElMessage.error('修正失败: ' + (error.response?.data?.message || error.message));
            } finally {
                submitting.value = false;
            }
        }
    });
};

onMounted(async () => {
    const orderId = route.params.orderId;
    const detailId = Number(route.params.detailId);
    const userId = authStore.state.user?.id;

    if (!userId) {
        ElMessage.error('无法获取当前用户信息，请重新登录。');
        loading.value = false;
        return;
    }
    form.approverId = userId; // 设置执行修正操作的用户ID

    if (orderId && detailId) {
        try {
            const res = await tradeApi.getTradeOrderDetails(orderId);
            const foundDetail = res.data.details?.find(d => d.id === detailId);

            if (foundDetail) {
                originalDetail.value = foundDetail;
                form.failedOrderDetailId = foundDetail.id;
                form.newFundCode = foundDetail.fundCode; // 默认填充原基金代码
                form.amount = foundDetail.amount; // 默认填充原金额
            } else {
                ElMessage.error('未找到指定的订单明细。');
            }
        } catch (error) {
            ElMessage.error('获取原始订单信息失败: ' + (error.response?.data?.message || error.message));
        } finally {
            loading.value = false;
        }
    } else {
        loading.value = false;
        ElMessage.error('URL参数不足，无法进行修正。');
    }
});
</script>

<style scoped>
.page-container {
    padding: 20px;
}

.mt-4 {
    margin-top: 1.5rem;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}
</style>